package com.dxb.test.thread;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 节点流管道实现线程间通信
 */
public class PipedStream {

    public static void main(String[] args) throws IOException {
        PipedInputStream input = new PipedInputStream();
        PipedOutputStream output = new PipedOutputStream();
        input.connect(output);
        new Thread(() -> {
            try {
                for (int i = 0; i < 1000; i++) {
                    System.out.println(Thread.currentThread().getName() + "->" + i);
                    output.write(String.valueOf(i).getBytes());
                    output.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, "output").start();

        new Thread(() -> {
            try {
                byte[] barr = new byte[20];

                int lenth = input.read(barr);
                while (lenth != -1) {
                    System.out.println(Thread.currentThread().getName() + "<-" + new String(barr, 0, lenth));
                    lenth = input.read(barr);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, "input").start();
    }
}
